#coding=utf-8
# @Author : shiqingshuai (shi_qingshuai@163.com)
# @Version : 1.0
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

from pymongo import MongoClient
import xlwt
def search_targets(f, targets):
    find1 = 0
    find2 = 0
    find3 = 0
    find4 = 0
    lines = ['', '', '', '']
    for line in f:
        line = line.strip()
        if '原告' in line and find1 == 0:
            find1 = 1
            lines[0] = line
            print line

        elif '被告' in line and find2 == 0:
            find2 = 1
            lines[1] = line
            print line

        if '上诉人' in line and find3 == 0 and '被上诉人' not in line:
            find3 = 1
            lines[2] = line
            print line

        if '被上诉人' in line and find4 == 0:
            find4 = 1
            lines[3] = line
            print line

        if find1 and find2 and find3 and find4:
            break

    return lines


def export_persons():
    client = MongoClient(host='127.0.0.1', port=27017)
    db = client['CASE']
    table = db['case_paths']
    print '读取case_paths表......'
    recs_cursor = table.find({"path":{"$regex": "/北京市"}})
    # recs_cursor.limit(10)
    print recs_cursor.count()

    book = xlwt.Workbook(encoding='utf-8')
    sheet = book.add_sheet('sheet1')
    titles = ['案例', '原告', '被告', '上诉人', '被上诉人']
    for index, title in enumerate(titles):
        sheet.write(0, index, title)

    row = 1
    for rec in recs_cursor:
        name = rec['_id']
        path = rec['path']
        #print 'path=======%s'%path
        true_path = '/Users/shiqingshuai/Desktop/劳动争议数据'+path
        try:
            fo = open(true_path)
        except Exception, e:
            print '打开文件失败！ %s' % str(e)
            continue
        print '==============start==========='
        lines = search_targets(fo, [])
        print '==============end============='

        location_path = 'C:'+path
        lines.insert(0, location_path)
        for index, line in enumerate(lines):
            if index == 0:
                link = 'HYPERLINK("%s";"%s")' % (location_path, name)
                sheet.write(row, 0, xlwt.Formula(link))
            else:
                sheet.write(row, index, line)
        row += 1

    book.save('persons.xls')

if __name__ == '__main__':
    export_persons()
